package com.demo.expertsystemdemo.mqtt;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lzb22
 */
@Slf4j
@Component
public class MqttCallbackHandler implements MessageHandler {

    private final MongoTemplate mongoTemplate;
    private final ApplicationContext applicationContext;

    public MqttCallbackHandler(ApplicationContext  applicationContext, MongoTemplate mongoTemplate) {
        this.applicationContext = applicationContext;
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    @ServiceActivator(inputChannel = "mqttInboundChannel")
    public void handleMessage(@NotNull Message<?> message) throws MessagingException {
        try {
/*            log.info("{},客户端号：{},主题：{}，QOS:{}，消息接收到的数据：\n{}",
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
                    message.getHeaders().get(MqttHeaders.ID),
                    message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC),
                    message.getHeaders().get(MqttHeaders.RECEIVED_QOS),
                    message.getPayload());*/
            String topic = (String) message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC);
            if (topic == null) {
                throw new Exception("接收或配置了错误的Topic信息");
            }
            String topicValue = topic.substring(topic.indexOf("/") + 1);
            String gatewayId = topicValue.substring(0,topicValue.indexOf("/"));
            String deviceName = topicValue.substring(topicValue.lastIndexOf("/")+1);
            String newCollectionName = gatewayId+"_"+deviceName;
            if(!mongoTemplate.collectionExists(newCollectionName)){
                mongoTemplate.createCollection(gatewayId+"_"+deviceName);
            }
            String playLoad = (String) message.getPayload();
            JSONObject dataObject = JSON.parseObject(playLoad);
            JSONArray dataArray = dataObject.getJSONArray("Data");
            for (Object o : dataArray) {
                JSONObject jsonData = JSON.parseObject(o.toString());
                mongoTemplate.save(jsonData, newCollectionName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("处理错误" + e.getMessage());
        }
    }


}
